package com.xinxin.base.entity;

import org.apache.http.HttpHost;
import org.apache.http.protocol.HttpContext;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;

/**
 * @author ys
 * @date 2021/5/29
 */
public class SSLConnectionSocketFactory extends org.apache.http.conn.ssl.SSLConnectionSocketFactory {

    public static final HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = (host, sslSession) -> true;

    public SSLConnectionSocketFactory(SSLContext sslContext) {
        super(sslContext);
    }

    public SSLConnectionSocketFactory(SSLContext sslContext, HostnameVerifier hostnameVerifier) {
        super(sslContext, hostnameVerifier);
    }

    @Override
    public Socket createSocket(HttpContext context) throws IOException {
        ProxyConfig proxyConfig = (ProxyConfig) context.getAttribute("proxy");
        Proxy.Type type = proxyConfig.getType();
        String hostname = proxyConfig.getHostname();
        Integer port = proxyConfig.getPort();

        if (type != Proxy.Type.DIRECT) {
            Proxy proxy = new Proxy(type, new InetSocketAddress(hostname, port));
            return new Socket(proxy);
        } else {
            return super.createSocket(context);
        }
    }

    @Override
    public Socket connectSocket(int connectTimeout,
                                Socket socket, HttpHost host,
                                InetSocketAddress remoteAddress, InetSocketAddress localAddress,
                                HttpContext context) throws IOException {
        ProxyConfig proxyConfig = (ProxyConfig) context.getAttribute("proxy");
        if (proxyConfig.getType() != Proxy.Type.DIRECT) {
            remoteAddress = InetSocketAddress.createUnresolved(host.getHostName(), remoteAddress.getPort());
        }

        return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
    }
}
